/*
 * Copyright (c) 2012, marco.tamburelli@gmail.com
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met: 
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.bmi.gwt.mi.server.channel;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.bmi.gwt.mi.server.core.queue.CallHandler;
import org.bmi.gwt.mi.server.core.queue.MiQueue;
import org.bmi.gwt.mi.server.core.queue.QueueState;
import org.bmi.gwt.mi.server.core.queue.QueuesManager;
import org.bmi.gwt.mi.server.core.queue.QueuesManager.BoundResult;
import org.bmi.gwt.mi.shared.Channel;
import org.bmi.gwt.mi.shared.MiProxyPublisher;
import org.bmi.gwt.mi.shared.MiPublisher;
import org.bmi.gwt.mi.shared.MiTransaction;
import org.bmi.gwt.mi.shared.MiTransactionPublisher;
import org.bmi.gwt.mi.shared.callbacks.AttributeCallback;
import org.bmi.gwt.mi.shared.callbacks.BindCallback;
import org.bmi.gwt.mi.shared.communication.attribute.AttributeValue;
import org.bmi.gwt.mi.shared.communication.call.Call;
import org.bmi.gwt.mi.shared.exceptions.BindNotAllowedException;
import org.bmi.gwt.mi.shared.exceptions.InvalidCredentialsException;
import org.bmi.gwt.mi.shared.util.ProxyFactory;
import org.bmi.gwt.mi.shared.util.WrapperFactory;

public final class ChannelServer extends Channel implements QueueState, CallHandler
{
	static protected Logger logger = Logger.getLogger(ChannelServer.class);

	private QueuesManager queuesManager;

	private String credentials;

	private boolean alive;

	/**
	 * Creates an object referencing a queuesManager. The created object is a
	 * {@link Channel} referencing a {@link MiQueue} element which:
	 * 
	 * 
	 * 1. The queuesManager has not yet defined credentials, in such case
	 * default credentials are provided and access right are warranted.
	 * 
	 * 2. Credentials are defined, in such case the access right is warranted
	 * only in case defined credentials match provided ones.
	 * 
	 * Warning: The provided logical queuesManager q, should be not null.
	 * 
	 * @param queueName The name of the pointing queuesManager.
	 * @param queuesManager The {@link QueuesManager} to which this object
	 *        points.
	 * @param proxyFactory A proxy factory to send calls.
	 * @param wrapperFactory a wrapper factory to receive calls.
	 * @param credentials Credentials certificate of the current user.
	 */
	protected ChannelServer(String queueName, QueuesManager queuesManager, ProxyFactory proxyFactory,
			WrapperFactory wrapperFactory, String credentials)
	{
		super();

		this.credentials = credentials;
		super.queueExpression = queueName;

		this.queuesManager = queuesManager;

		super.proxyFactory = proxyFactory;
		super.wrapperFactory = wrapperFactory;

		this.alive = true;
	}

	@Override
	public void bind(BindCallback callback)
	{
		if (super.bindAllowed)
		{
			BoundResult br = this.queuesManager.bind(this);

			if (br.success())
			{
				super.bindAllowed = true;
				super.bound = true;

				callback.onBound(this);
				br.fireEvents();
			}
			else
				callback.onError(new InvalidCredentialsException("Credentials to bind to queue '"
						+ super.queueExpression + "' aren't valid."));
		}
		else
			callback.onError(new BindNotAllowedException("Channel doesn't allow to bind to queue '"
					+ super.queueExpression + "'."));
	}

	@Override
	public void unbind(boolean discard)
	{
		if (super.bound) try
		{
			super.bound = false;
			this.queuesManager.unbind(super.queueExpression, this.credentials, discard);
		}
		catch (Throwable e)
		{}
	}

	@Override
	protected void onResponse(List<Call> calls) throws Exception
	{
		manageResponse(calls);
	}

	@Override
	protected MiPublisher provideMiPublisher(boolean transactional)
	{
		if (transactional)
			return new MiTransactionPublisher();
		else
			return new MiProxyPublisher()
			{
				@Override
				protected void publish(List<Call> calls)
				{
					try
					{
						ChannelServer.this.queuesManager.publish(super.broadChannel.getExpression(), calls);
					}
					catch (Exception e)
					{
						logger.error("[ChannelServer] an error occurred while publishing: ", e);
					}
				}
			};
	}

	@Override
	public MiTransaction createTransaction()
	{
		return new MiTransaction(this)
		{
			@Override
			protected void publish(List<Call> calls)
			{
				try
				{
					ChannelServer.this.queuesManager.publish(super.broadChannel.getExpression(), calls);
				}
				catch (Exception e)
				{
					logger.error("[ChannelServer] an error occurred while publishing: ", e);
				}
			}
		};
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T extends AttributeValue<?>> void getAttribute(String key, AttributeCallback<T> callback)
	{
		callback.onSuccess((T) super.attributes.get(key));
	}

	@Override
	public <T extends AttributeValue<?>> void setAttribute(String key, T value, AttributeCallback<T> callback)
	{
		if (super.bindAllowed)
		{
			super.attributes.put(key, value);
			callback.onSuccess(value);
		}
		else
			callback.onError(new InvalidCredentialsException("Impossible to update attribute of queue '"
					+ super.queueExpression + "' because provided credentials don't allow such operation."));
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T extends AttributeValue<?>> void removeAttribute(String key, AttributeCallback<T> callback)
	{
		if (super.bindAllowed)
			callback.onSuccess((T) super.attributes.remove(key));
		else
			callback.onError(new InvalidCredentialsException("Impossible to update attribute of queue '"
					+ super.queueExpression + "' because provided credentials don't allow such operation."));
	}

	@Override
	protected void finalize() throws Throwable
	{
		super.finalize();

		unbind();
		this.alive = false;
	}

	@Override
	public String getQueueName()
	{
		return super.queueExpression;
	}

	@Override
	public Map<String, AttributeValue<?>> getAttributes()
	{
		return super.attributes;
	}

	@Override
	public String getOwnerCredentials()
	{
		return this.credentials;
	}

	@Override
	public boolean isReplaceable()
	{
		return !this.alive;
	}

	@Override
	public void onCalls(String queueName, List<Call> elems)
	{
		try
		{
			this.manageResponse(elems);
		}
		catch (Exception e)
		{
			logger.error("[ChannelServer] Error while on applying calls", e);
		}
	}

	@Override
	public boolean canConsumeCalls()
	{
		return super.bindAllowed;
	}
}
